package mamikeji.liaowa.ui.activity.right;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.model.IPickerViewData;
import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import mamikeji.liaowa.R;
import mamikeji.liaowa.application.MyApplication;
import mamikeji.liaowa.bean.UpdateUserBean;
import mamikeji.liaowa.bean.UserBean;
import mamikeji.liaowa.bean.Wa_UserMSG_ListBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.AddWaActivity;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.activity.circle.FriendMSGActivity;
import mamikeji.liaowa.ui.activity.right.update.UpdateUserCodeActivity;
import mamikeji.liaowa.ui.activity.right.update.UpdateUserJieshaoActivity;
import mamikeji.liaowa.ui.activity.right.update.UpdateUserNameActivity;
import mamikeji.liaowa.ui.adapter.User_WaListAdapter;
import mamikeji.liaowa.utils.FileUtils;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.GlideCircleTransform;
import mamikeji.liaowa.widget.addressPick.GetJsonDataUtil;
import mamikeji.liaowa.widget.addressPick.JsonBean;
import mamikeji.liaowa.widget.refreshView.PtrlDownRefreshFrameLayout;
import mamikeji.liaowa.widget.selectorImage.MultiImageSelector;
import mamikeji.liaowa.widget.slidelistview.SilderListView;
import mamikeji.liaowa.widget.zxing.activity.CaptureActivity;
import mamikeji.liaowa.widget.zxing.utils.CommonUtil;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnCompressListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;


public class UserMSGActicity extends BaseActivity implements View.OnClickListener {
    private static final int REQUEST_CAMERA = 100;
    private static final int REQUEST_GALLERY = 101;
    private static final int RESULT_REQUEST_CODE = 102;

    private static final int MSG_LOAD_DATA = 103;
    private static final int MSG_LOAD_SUCCESS = 104;
    private static final int MSG_LOAD_FAILED = 105;

    //打开扫描界面请求码
    private int REQUEST_ZXING_CODE = 0xA1;

    private static final String TAG = "UserMSGActicity";
    public SimpleDraweeView imageView_dynamic_titleimg;
    public RelativeLayout relativeLayout_usermsg_nickname;
    public RelativeLayout relativeLayout_usermsg_sex;
    public RelativeLayout relativeLayout_usermsg_birthday;
    public RelativeLayout relativeLayout_usermsg_resident;
    public RelativeLayout relativeLayout_usermsg_phone;
    public RelativeLayout relativeLayout_usermsg_userjieshao;
    public RelativeLayout relativeLayout_usermsg_invitation_code;
    public RelativeLayout relativeLayout_usermsg_data;
    public ImageView imageView_usermsg_open;
    public TextView textView_usermsg_invitation_code;
    public TextView textView_usermsg_name;
    public TextView textView_usermsg_sex;
    public TextView textView_usermsg_sex_title;
    public TextView textView_usermsg_birthday;
    public TextView textView_usermsg_changzhudi;
    public TextView textView_usermsg_phone;
    public TextView textView_usermsg_jianjie;
    public TextView textView_usermsg_wanum;
    public SilderListView listView_usermsg_wa;
    private PtrlDownRefreshFrameLayout ptrlDownRefreshFrameLayout_usermsg_wa;

    public RelativeLayout relativeLayout_usermsg_foot_add;

    private User_WaListAdapter user_waListAdapter;
    private List<Wa_UserMSG_ListBean.UserbadyListEntity> userbadyListEntityList = new ArrayList<Wa_UserMSG_ListBean.UserbadyListEntity>();
    private List<Wa_UserMSG_ListBean.UserbadyListEntity> userbadyList;

    private View foot_view, header_view;

    private Dialog dialog, dialog_sex, dialog_delete_wa;
    private Button btn_userimg_camera, btn_userimg_album, btn_userimg_cancel;

    private boolean bool_open = false;

    /**
     * 创建一个以当前时间为名称的文件
     */
    private File tempFile = null;

    private static final int REQUEST_IMAGE = 2;

    private MultiStateView multiStateView_usermsg_wa;

    private RelativeLayout relativeLayout_usermsg_btnerror, relativeLayout_usermsg_query;
    private ImageView imageView_usermsg_sex_nan, imageView_usermsg_sex_nv;

    private Thread thread;
    private boolean isLoaded = false;

    private ArrayList<CardBean> cardSexItem = new ArrayList<>();
    private OptionsPickerView pvCustomOptions;

    //时间选择器
    TimePickerView pvTime;
    OptionsPickerView pvOptions;

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private int wa_position, wa_delete_id;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Glide
                            .with(UserMSGActicity.this)
                            .load((String) msg.obj)
                            .transform(new GlideCircleTransform(UserMSGActicity.this))
                            .crossFade()
                            .error(R.drawable.img_baobaotouxiang)
                            .into(imageView_dynamic_titleimg);
//                    imageView_dynamic_titleimg.setImageURI(Uri.parse((String) msg.obj));
                    ForToast.showToast("修改成功！");
                    hideLoading();
                    break;
                case 1:
                    ForToast.showToast("修改失败！");
                    hideLoading();
                    break;
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        showLoading();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    hideLoading();
                    isLoaded = true;
                    if (isLoaded) {
                        address_data();
                    } else {
                        ForToast.showToast("请重试！");
                    }
                    break;
                case MSG_LOAD_FAILED:
                    hideLoading();
                    ForToast.showToast("请重试！");
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_msg);
        getBase();
        setTitleLeftBtn();
        setTitleName(R.string.user_msg_title);
        init();
        initData();
        getWaList();
        userimg_dig();
        getListOnItemClick();
        initSexPicker();
    }

    private void init() {
        tempFile = new File(Environment.getExternalStorageDirectory(), getPhotoFileName());

        ptrlDownRefreshFrameLayout_usermsg_wa = (PtrlDownRefreshFrameLayout) findViewById(R.id.ptrlDownRefreshFrameLayout_usermsg_wa);
        listView_usermsg_wa = (SilderListView) findViewById(R.id.listView_usermsg_wa);

        //添加头部布局
        header_view = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.item_usermsg_wa_header, null);
        listView_usermsg_wa.addHeaderView(header_view, null, false);

        foot_view = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.item_usermsg_wa_foot, null);
        listView_usermsg_wa.addFooterView(foot_view, null, false);

        user_waListAdapter = new User_WaListAdapter(userbadyListEntityList, this);

        listView_usermsg_wa.setAdapter(user_waListAdapter);

        relativeLayout_usermsg_invitation_code = (RelativeLayout) foot_view.findViewById(R.id.relativeLayout_usermsg_invitation_code);
        textView_usermsg_invitation_code = (TextView) foot_view.findViewById(R.id.textView_usermsg_invitation_code);
        relativeLayout_usermsg_foot_add = (RelativeLayout) foot_view.findViewById(R.id.relativeLayout_usermsg_foot_add);
        relativeLayout_usermsg_foot_add.setOnClickListener(this);

        relativeLayout_usermsg_data = (RelativeLayout) header_view.findViewById(R.id.relativeLayout_usermsg_data);
        imageView_usermsg_open = (ImageView) header_view.findViewById(R.id.imageView_usermsg_open);
        imageView_dynamic_titleimg = (SimpleDraweeView) header_view.findViewById(R.id.imageView_dynamic_header_titleimg_sel);
        relativeLayout_usermsg_nickname = (RelativeLayout) header_view.findViewById(R.id.relativeLayout_usermsg_header_nickname);
        relativeLayout_usermsg_sex = (RelativeLayout) header_view.findViewById(R.id.relativeLayout_usermsg_sex);
        relativeLayout_usermsg_birthday = (RelativeLayout) header_view.findViewById(R.id.relativeLayout_usermsg_birthday);
        relativeLayout_usermsg_resident = (RelativeLayout) header_view.findViewById(R.id.relativeLayout_usermsg_resident);
        relativeLayout_usermsg_phone = (RelativeLayout) header_view.findViewById(R.id.relativeLayout_usermsg_phone);
        relativeLayout_usermsg_userjieshao = (RelativeLayout) header_view.findViewById(R.id.relativeLayout_usermsg_userjieshao);

        textView_usermsg_wanum = (TextView) header_view.findViewById(R.id.textView_usermsg_wanum);
        textView_usermsg_name = (TextView) header_view.findViewById(R.id.textView_usermsg_name);
        textView_usermsg_sex = (TextView) header_view.findViewById(R.id.textView_usermsg_sex);
        textView_usermsg_sex_title = (TextView) header_view.findViewById(R.id.textView_usermsg_sex_title);
        textView_usermsg_birthday = (TextView) header_view.findViewById(R.id.textView_usermsg_birthday);
        textView_usermsg_changzhudi = (TextView) header_view.findViewById(R.id.textView_usermsg_changzhudi);
        textView_usermsg_phone = (TextView) header_view.findViewById(R.id.textView_usermsg_phone);
        textView_usermsg_jianjie = (TextView) header_view.findViewById(R.id.textView_usermsg_jianjie);

        relativeLayout_usermsg_data.setOnClickListener(this);
        imageView_usermsg_open.setOnClickListener(this);
        imageView_dynamic_titleimg.setOnClickListener(this);
        relativeLayout_usermsg_nickname.setOnClickListener(this);
        relativeLayout_usermsg_sex.setOnClickListener(this);
        relativeLayout_usermsg_birthday.setOnClickListener(this);
        relativeLayout_usermsg_resident.setOnClickListener(this);
        relativeLayout_usermsg_phone.setOnClickListener(this);
        relativeLayout_usermsg_userjieshao.setOnClickListener(this);
        relativeLayout_usermsg_invitation_code.setOnClickListener(this);

        time_data();
        getDigLog();

        multiStateView_usermsg_wa = (MultiStateView) findViewById(R.id.multiStateView_usermsg_wa);

        multiStateView_usermsg_wa.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateView_usermsg_wa.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        getWaList();
                    }
                });

    }

    /**
     * /**
     * 初始化数据
     */
    private void initData() {
        textView_usermsg_sex_title.setText(ForPreference.getString(ForContents.USER_SEX).equals("1")
                ? R.string.user_msg_sex_did : R.string.user_msg_sex_mom);

        Glide
                .with(this)
                .load(ForPreference.getString(ForContents.USER_HEADERURL))
                .transform(new GlideCircleTransform(UserMSGActicity.this))
                .crossFade()
                .error(R.drawable.img_baobaotouxiang)
                .into(imageView_dynamic_titleimg);
//        imageView_dynamic_titleimg.setImageURI(Uri.parse(ForPreference.getString(ForContents.USER_HEADERURL)));
        textView_usermsg_name.setText(ForPreference.getString(ForContents.USER_NAME));
        textView_usermsg_sex.setText(ForPreference.getString(ForContents.USER_SEX).equals("1")
                ? R.string.user_msg_sex_nan : R.string.user_msg_sex_nv);
        textView_usermsg_birthday.setText(ForPreference.getString(ForContents.USER_BIRTHDAY).split("a").length > 1 ? getBirthdTime() : ForPreference.getString(ForContents.USER_BIRTHDAY));
        textView_usermsg_changzhudi.setText(ForPreference.getString(ForContents.USER_ADDRESS).equals("") ? "未设置" : ForPreference.getString(ForContents.USER_ADDRESS));
        textView_usermsg_phone.setText(ForPreference.getString(ForContents.USER_PHONE));
        textView_usermsg_jianjie.setText(ForPreference.getString(ForContents.USER_DESCRIBE));

        textView_usermsg_invitation_code.setText(ForPreference.getString(ForContents.USER_activationcode).equals("code_null") ?
                "" : ForPreference.getString(ForContents.USER_activationcode));
    }

    public String getBirthdTime() {
        String newStr = ForPreference.getString(ForContents.USER_BIRTHDAY)
                .substring(ForPreference.getString(ForContents.USER_BIRTHDAY).indexOf("(") + 1,
                        ForPreference.getString(ForContents.USER_BIRTHDAY).lastIndexOf(")"));
        Long datatime = Long.valueOf(newStr);
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return sDateFormat.format(new Date(datatime));
    }

    public void getListOnItemClick() {
        ptrlDownRefreshFrameLayout_usermsg_wa.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, listView_usermsg_wa, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                initData();
                getWaList();
            }
        });
        listView_usermsg_wa.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (ForPreference.getString(ForContents.WA_DEFAULT_ID).equals(userbadyListEntityList.get(i - 1).getBabyid())) {
                    Intent intent = new Intent(UserMSGActicity.this, BabyMSGActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(ForContents.WA_DEFAULT_ID, ForPreference.getString(ForContents.WA_DEFAULT_ID));
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    getChangeWa_default(userbadyListEntityList.get(i - 1).getId(), i);
                }
            }
        });

        user_waListAdapter.setOnItemClickListener(new User_WaListAdapter.OnItemClickListener() {
            @Override
            public void onDeleteClick(int wa_id, int position) {
                if (ForPreference.getString(ForContents.WA_DEFAULT_ID).equals(userbadyListEntityList.get(position).getBabyid())) {
//                    ForToast.showToast(R.string.user_msg_delete_wa_canel);
                    ForToast.showToast("不可删除，当前娃！");
                } else {
                    dialog_delete_wa.show();
                    wa_position = position;
                    wa_delete_id = wa_id;
                }
            }
        });
    }

    private TextView textView_dig_cache_text;
    private RelativeLayout relativeLayout_set_dig_btnerror, relativeLayout_set_dig_query;

    private void getDigLog() {
        dialog_delete_wa = new Dialog(UserMSGActicity.this, R.style.DialogLoading);
        View inflate = LayoutInflater.from(UserMSGActicity.this).inflate(R.layout.diglog_set_clearcache, null);
        dialog_delete_wa.setContentView(inflate);

        textView_dig_cache_text = (TextView) inflate.findViewById(R.id.textView_dig_cache_text);
        relativeLayout_set_dig_btnerror = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_set_dig_btnerror);
        relativeLayout_set_dig_query = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_set_dig_query);

        textView_dig_cache_text.setText("是否删除？");

        relativeLayout_set_dig_btnerror.setOnClickListener(this);
        relativeLayout_set_dig_query.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.imageView_usermsg_open:
                bool_open = !bool_open;
                imageView_usermsg_open.setImageResource(bool_open ? R.drawable.icon_qianjin_n : R.drawable.icon_xiangxia_n);
                if (bool_open) {
                    user_waListAdapter.setList(new ArrayList<Wa_UserMSG_ListBean.UserbadyListEntity>());
                } else {
                    user_waListAdapter.setList(userbadyListEntityList);
                }
                user_waListAdapter.notifyDataSetChanged();
                break;
            case R.id.relativeLayout_set_dig_btnerror:
                dialog_delete_wa.hide();
                break;
            case R.id.relativeLayout_set_dig_query:
                dialog_delete_wa.hide();
                getDeleteWa();
                break;
            case R.id.relativeLayout_usermsg_sex:
                pvCustomOptions.show();
                break;
            case R.id.relativeLayout_usermsg_invitation_code:
                if (ForPreference.getString(ForContents.USER_activationcode).equals("code_null")) {
                    intent = new Intent(UserMSGActicity.this, UpdateUserCodeActivity.class);
                } else {
                    //打开二维码扫描界面
                    if (CommonUtil.isCameraCanUse()) {
                        Intent mintent = new Intent(UserMSGActicity.this, CaptureActivity.class);
                        startActivityForResult(mintent, REQUEST_ZXING_CODE);
                    } else {
                        ForToast.showToast("请打开摄像头权限！");
                    }
                }
                break;
            case R.id.imageView_dynamic_header_titleimg_sel:
                dialog.show();
                break;
            case R.id.relativeLayout_usermsg_header_nickname:
                intent = new Intent(UserMSGActicity.this, UpdateUserNameActivity.class);
                intent.putExtra(ForContents.USER_NAME, ForPreference.getString(ForContents.USER_NAME));
                break;
            case R.id.relativeLayout_usermsg_birthday:
                pvTime.show();
                break;
            case R.id.relativeLayout_usermsg_userjieshao:
                intent = new Intent(UserMSGActicity.this, UpdateUserJieshaoActivity.class);
                intent.putExtra(ForContents.USER_DESCRIBE, ForPreference.getString(ForContents.USER_DESCRIBE));
                break;
            case R.id.relativeLayout_usermsg_data:
                MobclickAgent.onEvent(this,"PersonalDataPreviewCard");//个人资料-预览资料卡
                intent = new Intent(UserMSGActicity.this, FriendMSGActivity.class);
                intent.putExtra(HttpKey.Friend_MSG_friendcode, ForPreference.getString(ForContents.USER_CODE));
                break;
            case R.id.relativeLayout_usermsg_foot_add:
                MobclickAgent.onEvent(this,"PersonalDataAdd");//个人资料-添加宝宝
                intent = new Intent(UserMSGActicity.this, AddWaActivity.class);
                break;
            case R.id.btn_userimg_camera:
                dialog.hide();
                photo();
                break;
            case R.id.btn_userimg_album:
                dialog.hide();
                MultiImageSelector.create(this)
                        .showCamera(false) // 是否显示相机. 默认为显示
                        .count(1) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                        .single() //单选
                        .start(this, REQUEST_GALLERY);
                break;
            case R.id.btn_userimg_cancel:
                dialog.hide();
                break;
            case R.id.relativeLayout_usermsg_resident:
                if (isLoaded) {
                    pvOptions.show();
                } else {
                    handler.sendEmptyMessage(MSG_LOAD_DATA);
                }
                break;
        }
        if (intent != null)
            startActivity(intent);
    }

    //删除娃
    private void getDeleteWa() {
        showLoading();

        ForHttp.getMsg(HttpApi.ROOT_PATH + HttpApi.DELETE_USERBADY
                        + "?" + HttpKey.WA_DELETE_ID + "=" + wa_delete_id
                , new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        ForLog.i(TAG, e.getMessage());
                        ForToast.showToast(R.string.intent_error);
                        hideLoading();
                    }

                    @Override
                    public void onResponse(String response) {
                        ForLog.i(TAG, response);
                        hideLoading();
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString(HttpKey.STATUS);
                            if ("200".equals(status)) {
                                --waNum;
                                textView_usermsg_wanum.setText("" + waNum);
                                userbadyListEntityList.remove(wa_position);
                                user_waListAdapter.notifyDataSetChanged();

                                //判断是否删除娃
                                ForPreference.putBoolean(ForContents.DELETE_WA_ID, true);
                            } else {
                                ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    private void initJsonData() {//解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        handler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public void address_data() {
        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() + "-" +
                        options2Items.get(options1).get(options2) + "-" +
                        options3Items.get(options1).get(options2).get(options3);

                geUpdateUserAddress(tx);
            }
        })

                .setTitleText("")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setCancelColor(0xffff94ae)
                .setSubmitColor(0xffff94ae)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    public void time_data() {
        boolean[] booleen = new boolean[]{true, true, true, false, false, false};
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                geUpdateUserMSG(getTime(date));
            }
        })
                .setType(booleen)//默认全部显示
                .setLabel("", "", "", "", "", "")
                .setCancelColor(0xffff94ae)
                .setSubmitColor(0xffff94ae)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
    }

    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private int waNum = 0;

    /**
     * 获取娃集合
     */
    public void getWaList() {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.WA_LIST_USERID, ForPreference.getString(ForContents.USER_CODE));
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.USERBADY_LIST, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateView_usermsg_wa.setViewState(MultiStateView.VIEW_STATE_ERROR);
                ptrlDownRefreshFrameLayout_usermsg_wa.refreshComplete();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                ptrlDownRefreshFrameLayout_usermsg_wa.refreshComplete();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        Wa_UserMSG_ListBean waUserMSGListBean = new Gson().fromJson(response, Wa_UserMSG_ListBean.class);
                        if (waUserMSGListBean.getUserbadyList() != null) {
                            if (waUserMSGListBean.getUserbadyList().size() > 0) {
                                userbadyList = waUserMSGListBean.getUserbadyList();
                                waNum = userbadyList.size();
                                textView_usermsg_wanum.setText("" + waNum);

                                userbadyListEntityList.clear();
                                userbadyListEntityList.addAll(userbadyList);
//                                for (int i = 0; i < userbadyListEntityList.size(); i++) {
//                                    if (ForPreference.getString(ForContents.WA_DEFAULT_ID).equals(userbadyListEntityList.get(i).getId() + "")) {
//                                        userbadyListEntityList.remove(i);
//                                    }
//                                }

                                user_waListAdapter.setList(userbadyListEntityList);
                                multiStateView_usermsg_wa.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                            } else {
                                multiStateView_usermsg_wa.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                            }
                        } else {
                            multiStateView_usermsg_wa.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    } else {
                        multiStateView_usermsg_wa.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 修改个人信息，生日
     */
    public void geUpdateUserMSG(final String birthTime) {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.UPDATE_USERMSG_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.UPDATE_USERMSG_BIRTHDAY, birthTime);
        formMap.put(HttpKey.UPDATE_USERMSG_NICKNAME, "");
        formMap.put(HttpKey.UPDATE_USERMSG_AREA, "");
        formMap.put(HttpKey.UPDATE_USERMSG_DESCRIBE, "");
        formMap.put(HttpKey.UPDATE_USERMSG_SEX, "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.UPLOAD_USER_MSG, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        UserBean userBean = new Gson().fromJson(response, UserBean.class);
                        ForPreference.putString(ForContents.USER_BIRTHDAY, birthTime);
                        textView_usermsg_birthday.setText(ForPreference.getString(ForContents.USER_BIRTHDAY));
                    }
                    ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    hideLoading();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void userimg_dig() {
        dialog = new Dialog(UserMSGActicity.this, R.style.ActionSheetDialogStyle);
        View inflate = LayoutInflater.from(UserMSGActicity.this).inflate(R.layout.dialog_usermsg_img, null);

        btn_userimg_camera = (Button) inflate.findViewById(R.id.btn_userimg_camera);
        btn_userimg_album = (Button) inflate.findViewById(R.id.btn_userimg_album);
        btn_userimg_cancel = (Button) inflate.findViewById(R.id.btn_userimg_cancel);

        btn_userimg_camera.setOnClickListener(this);
        btn_userimg_album.setOnClickListener(this);
        btn_userimg_cancel.setOnClickListener(this);

        dialog.setContentView(inflate);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;
        lp.width = (int) getResources().getDisplayMetrics().widthPixels - 30; // 宽度
        dialogWindow.setAttributes(lp);
    }

    /**
     * 修改个人信息，性别
     */
    public void geUpdateUserSEX(int options) {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.UPDATE_USERMSG_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.UPDATE_USERMSG_BIRTHDAY, "");
        formMap.put(HttpKey.UPDATE_USERMSG_NICKNAME, "");
        formMap.put(HttpKey.UPDATE_USERMSG_AREA, "");
        formMap.put(HttpKey.UPDATE_USERMSG_DESCRIBE, "");
        formMap.put(HttpKey.UPDATE_USERMSG_SEX, options + "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.UPLOAD_USER_MSG, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        UserBean userBean = new Gson().fromJson(response, UserBean.class);
                        ForPreference.putString(ForContents.USER_SEX, userBean.getUser().getSex());
                        textView_usermsg_sex.setText(ForPreference.getString(ForContents.USER_SEX).equals("1") ? "男" : "女");
                    }
                    ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    hideLoading();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 修改个人信息，地址
     */
    public void geUpdateUserAddress(String address) {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.UPDATE_USERMSG_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.UPDATE_USERMSG_BIRTHDAY, "");
        formMap.put(HttpKey.UPDATE_USERMSG_NICKNAME, "");
        formMap.put(HttpKey.UPDATE_USERMSG_AREA, address);
        formMap.put(HttpKey.UPDATE_USERMSG_DESCRIBE, "");
        formMap.put(HttpKey.UPDATE_USERMSG_SEX, "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.UPLOAD_USER_MSG, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        UserBean userBean = new Gson().fromJson(response, UserBean.class);
                        ForPreference.putString(ForContents.USER_ADDRESS, userBean.getUser().getArea());
                        textView_usermsg_changzhudi.setText(ForPreference.getString(ForContents.USER_ADDRESS));
                    }
                    ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    hideLoading();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 使用系统当前日期加以调整作为照片的名称
     *
     * @return 照片的名称
     */
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss", Locale.getDefault());
        return dateFormat.format(date) + ".jpg";
    }

    private String mImageFileName;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_GALLERY) {
                List<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                if (mSelectPath != null && mSelectPath.size() > 0) {
                    Uri uri = Uri.fromFile(new File(mSelectPath.get(0)));
                    startPhotoZoom(uri);
                }
            } else if (requestCode == REQUEST_CAMERA) {
                File file = new File(Environment.getExternalStorageDirectory() + "/" + mImageFileName);
                Uri uri = Uri.fromFile(file);
                startPhotoZoom(uri);
            } else if (requestCode == RESULT_REQUEST_CODE) {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap bitmap = extras.getParcelable("data");
                    //Drawable drawable = new BitmapDrawable(this.getResources(), bitmap);
//                    imageView_dynamic_titleimg.setImageDrawable(drawable);
                    FileUtils.saveBitmap(bitmap, "avatar");
                    File file = new File(FileUtils.SDPATH + "avatar.jpg");
                    if (file != null) {
                        compress(file);
                    }
                }
            } else if (requestCode == REQUEST_ZXING_CODE) {
                //扫描结果回调
                Bundle bundle = data.getExtras();
                String scanResult = bundle.getString("qr_scan_result") + "&usercode=" + ForPreference.getString(ForContents.USER_CODE);
                Intent intent = new Intent(UserMSGActicity.this, CodeActivity.class);
                intent.putExtra("activity_code_url", scanResult);
                startActivity(intent);
            }
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 340);
        intent.putExtra("outputY", 340);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    /**
     * 更新默认娃娃
     *
     * @return
     */
    public void getChangeWa_default(final int waID, final int i) {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.WA_DEFAULT_USERID, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.WA_DEFAULT_BABYID, waID + "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.WA_DEFAULT_BODY, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG + "_aasda", response);
                hideLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        //判断是否切换娃
                        ForPreference.putBoolean(ForContents.WHERE_WA_ID, true);
                        //记录默选娃ID
                        ForPreference.putString(ForContents.WA_DEFAULT_ID, waID + "");

                        userbadyListEntityList.clear();
                        userbadyListEntityList.addAll(userbadyList);
//                        for (int i = 0; i < userbadyListEntityList.size(); i++) {
//                            if (ForPreference.getString(ForContents.WA_DEFAULT_ID).equals(userbadyListEntityList.get(i).getId() + "")) {
//                                userbadyListEntityList.remove(i);
//                            }
//                        }
                        user_waListAdapter.notifyDataSetChanged();

                        Intent intent = new Intent(UserMSGActicity.this, BabyMSGActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString(ForContents.WA_DEFAULT_ID, waID + "");
                        intent.putExtras(bundle);
                        startActivity(intent);

                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void photo() {
        // 随机缓存照片名
        mImageFileName = FileUtils.getFileNameForSystemTime(".jpg");
        // 首先判断SD卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), mImageFileName)));
            startActivityForResult(intent, REQUEST_CAMERA);
        } else {
            ForToast.showToast("内存卡不存在");
        }
    }

    private void compress(File f) {
        Luban.compress(this, f)
                .putGear(Luban.CUSTOM_GEAR)
                .setMaxSize(300)
                .launch(new OnCompressListener() {
                    @Override
                    public void onStart() {}

                    @Override
                    public void onSuccess(File file) {
                        uploadImage(file);
                    }

                    @Override
                    public void onError(Throwable e) {
                        ForToast.showToast("压缩失败");
                        ForLog.i("compresscompresscompress", "" + e.toString());
                    }
                });
    }

    private void uploadImage(File file) {
        showLoading();
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("file", "file.jpg", RequestBody.create(MultipartBody.FORM, file));
        builder.addFormDataPart("id", ForPreference.getString(ForContents.USER_CODE));
        MultipartBody body = builder.build();

        OkHttpClient okHttpClient = new OkHttpClient();
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(HttpApi.ROOT_PATH + HttpApi.UPLOAD_IMG)
                .post(body)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("失败:" + e.toString());
                hideLoading();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                ForLog.i("json_json", json + "");
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    String status = jsonObject.getString(HttpKey.STATUS);

                    Message message = Message.obtain();

                    if ("200".equals(status)) {
                        UpdateUserBean updateUserBean = new Gson().fromJson(json, UpdateUserBean.class);
                        message.what = 0;
                        message.obj = updateUserBean.getUser().getAvatar();
                        handler.sendMessage(message);
                        ForPreference.putString(ForContents.USER_HEADERURL, updateUserBean.getUser().getAvatar());
                    } else {
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 性别选择器初始化
     */
    private void initSexPicker() {
        cardSexItem.add(new CardBean(0, "女"));
        cardSexItem.add(new CardBean(1, "男"));

        pvCustomOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                geUpdateUserSEX(options1);
            }
        })
                .isDialog(false)
                .setCancelColor(0xffff94ae)
                .setSubmitColor(0xffff94ae)
                .build();
        pvCustomOptions.setPicker(cardSexItem);//添加数据

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Glide
                .with(this)
                .load(ForPreference.getString(ForContents.USER_HEADERURL))
                .transform(new GlideCircleTransform(UserMSGActicity.this))
                .crossFade()
                .error(R.drawable.img_baobaotouxiang)
                .into(imageView_dynamic_titleimg);
//        imageView_dynamic_titleimg.setImageURI(Uri.parse(HttpApi.ROOT_PATH + ForPreference.getString(ForContents.USER_HEADERURL)));
        textView_usermsg_name.setText(ForPreference.getString(ForContents.USER_NAME));
        textView_usermsg_sex.setText(ForPreference.getString(ForContents.USER_SEX).equals("1") ? "男" : "女");

        textView_usermsg_birthday.setText(ForPreference.getString(ForContents.USER_BIRTHDAY).split("a").length > 1 ? "未设置" : ForPreference.getString(ForContents.USER_BIRTHDAY));
        textView_usermsg_changzhudi.setText(ForPreference.getString(ForContents.USER_ADDRESS).equals("") ? "未设置" : ForPreference.getString(ForContents.USER_ADDRESS));

        textView_usermsg_phone.setText(ForPreference.getString(ForContents.USER_PHONE));
        textView_usermsg_jianjie.setText(ForPreference.getString(ForContents.USER_DESCRIBE));

        textView_usermsg_invitation_code.setText(ForPreference.getString(ForContents.USER_activationcode).equals("code_null") ?
                "" : ForPreference.getString(ForContents.USER_activationcode));
    }

    class CardBean implements IPickerViewData {
        int id;
        String cardNo;

        public CardBean(int id, String cardNo) {
            this.id = id;
            this.cardNo = cardNo;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getCardNo() {
            return cardNo;
        }

        public void setCardNo(String cardNo) {
            this.cardNo = cardNo;
        }

        @Override
        public String getPickerViewText() {
            return cardNo;
        }
    }

}
